import pygame
import random
import sys
import time
import os

# 初始化pygame
pygame.init()

# 游戏常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 700
GRID_SIZE = 10
CELL_SIZE = 50
GRID_OFFSET_X = (SCREEN_WIDTH - GRID_SIZE * CELL_SIZE) // 2
GRID_OFFSET_Y = 100
GAME_DURATION = 60  # 游戏时长（秒）

# 颜色定义
BACKGROUND = (240, 240, 240)
GRID_COLOR = (200, 200, 200)
COLORS = [
    (255, 100, 100),  # 红色
    (100, 255, 100),  # 绿色
    (100, 100, 255),  # 蓝色
    (255, 255, 100),  # 黄色
    (255, 100, 255),  # 紫色
    (100, 255, 255),  # 青色
]

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Color Blast - 彩色方块消消乐")


# 字体设置 - 使用系统中文字体
def get_chinese_font(size):
    """获取中文字体，兼容不同Windows系统"""
    # 常见的中文字体路径
    font_paths = [
        "C:/Windows/Fonts/simhei.ttf",  # 黑体
        "C:/Windows/Fonts/simsun.ttc",  # 宋体
        "C:/Windows/Fonts/msyh.ttc",  # 微软雅黑
        "C:/Windows/Fonts/simkai.ttf",  # 楷体
    ]

    for path in font_paths:
        if os.path.exists(path):
            try:
                return pygame.font.Font(path, size)
            except:
                continue

    # 如果找不到中文字体，使用默认字体（可能不支持中文）
    return pygame.font.SysFont(None, size)


# 创建字体实例
font = get_chinese_font(36)
small_font = get_chinese_font(24)
title_font = get_chinese_font(48)


class Game:
    def __init__(self):
        self.grid = [[0 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
        self.score = 0
        self.start_time = time.time()
        self.fill_grid()

    def fill_grid(self):
        """填充网格随机颜色"""
        for i in range(GRID_SIZE):
            for j in range(GRID_SIZE):
                self.grid[i][j] = random.randint(0, len(COLORS) - 1)

    def get_connected_cells(self, row, col):
        """获取相连的同色方块"""
        color = self.grid[row][col]
        if color == -1:  # 空白方块
            return []

        visited = [[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
        connected = []
        stack = [(row, col)]

        while stack:
            r, c = stack.pop()
            if r < 0 or r >= GRID_SIZE or c < 0 or c >= GRID_SIZE:
                continue
            if visited[r][c] or self.grid[r][c] != color:
                continue

            visited[r][c] = True
            connected.append((r, c))

            # 检查四个方向
            stack.append((r + 1, c))
            stack.append((r - 1, c))
            stack.append((r, c + 1))
            stack.append((r, c - 1))

        return connected if len(connected) >= 2 else []

    def remove_cells(self, cells):
        """移除方块并计算分数"""
        if not cells:
            return

        # 计算分数（相连方块数量的平方）
        self.score += len(cells) ** 2

        # 移除方块
        for r, c in cells:
            self.grid[r][c] = -1

        # 方块下落
        for col in range(GRID_SIZE):
            empty_cells = []
            for row in range(GRID_SIZE - 1, -1, -1):
                if self.grid[row][col] == -1:
                    empty_cells.append(row)
                elif empty_cells:
                    # 移动方块到最低的空位置
                    lowest_empty = empty_cells.pop(0)
                    self.grid[lowest_empty][col] = self.grid[row][col]
                    self.grid[row][col] = -1
                    empty_cells.append(row)

        # 从左到右填充空白列
        empty_cols = []
        for col in range(GRID_SIZE):
            if all(self.grid[row][col] == -1 for row in range(GRID_SIZE)):
                empty_cols.append(col)

        for empty_col in empty_cols:
            for col in range(empty_col, GRID_SIZE - 1):
                for row in range(GRID_SIZE):
                    self.grid[row][col] = self.grid[row][col + 1]

            # 最右边的列设为空白
            for row in range(GRID_SIZE):
                self.grid[row][GRID_SIZE - 1] = -1

    def draw(self):
        """绘制游戏界面"""
        screen.fill(BACKGROUND)

        # 绘制游戏标题
        title_text = title_font.render("彩色方块消消乐", True, (50, 50, 50))
        screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 10))

        # 绘制分数
        score_text = font.render(f"分数: {self.score}", True, (0, 0, 0))
        screen.blit(score_text, (20, 70))

        # 绘制剩余时间
        elapsed_time = time.time() - self.start_time
        remaining_time = max(0, GAME_DURATION - elapsed_time)
        time_text = font.render(f"时间: {int(remaining_time)}秒", True, (0, 0, 0))
        screen.blit(time_text, (SCREEN_WIDTH - 150, 70))

        # 绘制网格
        for i in range(GRID_SIZE):
            for j in range(GRID_SIZE):
                x = GRID_OFFSET_X + j * CELL_SIZE
                y = GRID_OFFSET_Y + i * CELL_SIZE

                if self.grid[i][j] != -1:
                    color_idx = self.grid[i][j]
                    pygame.draw.rect(screen, COLORS[color_idx],
                                     (x, y, CELL_SIZE, CELL_SIZE))
                    pygame.draw.rect(screen, (50, 50, 50),
                                     (x, y, CELL_SIZE, CELL_SIZE), 1)
                else:
                    pygame.draw.rect(screen, BACKGROUND,
                                     (x, y, CELL_SIZE, CELL_SIZE))

        # 绘制网格线
        for i in range(GRID_SIZE + 1):
            # 垂直线
            pygame.draw.line(screen, GRID_COLOR,
                             (GRID_OFFSET_X + i * CELL_SIZE, GRID_OFFSET_Y),
                             (GRID_OFFSET_X + i * CELL_SIZE, GRID_OFFSET_Y + GRID_SIZE * CELL_SIZE))
            # 水平线
            pygame.draw.line(screen, GRID_COLOR,
                             (GRID_OFFSET_X, GRID_OFFSET_Y + i * CELL_SIZE),
                             (GRID_OFFSET_X + GRID_SIZE * CELL_SIZE, GRID_OFFSET_Y + i * CELL_SIZE))

        # 游戏结束提示
        if remaining_time <= 0:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            screen.blit(overlay, (0, 0))

            game_over_text = title_font.render("游戏结束!", True, (255, 255, 255))
            final_score_text = font.render(f"最终分数: {self.score}", True, (255, 255, 255))
            restart_text = small_font.render("按R键重新开始", True, (255, 255, 255))

            screen.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 2 - 60))
            screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2))
            screen.blit(restart_text, (SCREEN_WIDTH // 2 - restart_text.get_width() // 2, SCREEN_HEIGHT // 2 + 40))

    def is_game_over(self):
        """检查游戏是否结束"""
        elapsed_time = time.time() - self.start_time
        return elapsed_time >= GAME_DURATION

    def restart(self):
        """重新开始游戏"""
        self.grid = [[0 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
        self.score = 0
        self.start_time = time.time()
        self.fill_grid()


# 创建游戏实例
game = Game()

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if not game.is_game_over():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    x, y = event.pos
                    # 检查点击是否在网格内
                    if (GRID_OFFSET_X <= x < GRID_OFFSET_X + GRID_SIZE * CELL_SIZE and
                            GRID_OFFSET_Y <= y < GRID_OFFSET_Y + GRID_SIZE * CELL_SIZE):
                        col = (x - GRID_OFFSET_X) // CELL_SIZE
                        row = (y - GRID_OFFSET_Y) // CELL_SIZE

                        # 获取相连的方块并移除
                        connected = game.get_connected_cells(row, col)
                        game.remove_cells(connected)
        else:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:  # 按R键重新开始
                    game.restart()

    # 绘制游戏
    game.draw()
    pygame.display.flip()

    # 控制帧率
    pygame.time.Clock().tick(60)

pygame.quit()
sys.exit()